<?php

require_once('class_form_element.php');

/*
  Given a mysql table with links between records which represent a tree
  structure, generate a select element with indentation to show that structure.
*/
class TreeSelectElement extends SelectElement
{
  const SPACER = '&nbsp;&nbsp;';

  public function __construct($name, $label = NULL, $table, $keyCol, $valueCol,
      $parentKeyCol, $database = NULL)
  {
    parent::__construct($name, $label);
    $mysqlFrom = ($database == NULL) ? $table : "$database.$table";
    $result = mysql_query("SELECT $keyCol, $valueCol, $parentKeyCol
                           FROM $mysqlFrom") or die(mysql_error());
    while (list($key, $value, $parentKey) = mysql_fetch_array($result)) {
      $this->options[] = new TreeSelectOption($key, $value, $parentKey);
    }
  }

  public function displayElement()
  {
    $this->setAttribute('value', null);
    echo $this->getFormElementHTML('select', false);
    $this->displayOptions();
    echo "</select>\n";
  }

  protected function displayOptions($parentKey = 0, $depth = 0)
  {
    foreach ($this->options as $option) {
      if ($option->parentKey == $parentKey) {
        $key = $option->key;
        $value = str_repeat(self::SPACER, $depth) . $option->value;
        $selected = ($this->hasValue($key)) ? ' selected="selected"' : '';

        echo "<option value=\"$key\"$selected>$value</option>\n";
        $this->displayOptions($option->key, $depth + 1);
      }
    }
  }
}

class TreeSelectOption
{
  public $key;
  public $value;
  public $parentKey;

  public function __construct($key, $value, $parentKey)
  {
    $this->key = $key;
    $this->value = $value;
    $this->parentKey = $parentKey;
  }
}


?>